#ifndef __NATSUME_Singleton_h__
#define __NATSUME_Singleton_h__

#include <cstdlib>
#include <iostream>
#include <pthread.h>

// Singleton: 单例设计模式的模板
template <typename Object>
class Singleton {
    public:
        template <typename... Args>
        static Object *
        getInstance(Args... args) {
            if (m_pInstance == nullptr) {
                m_pInstance = new Object(args ...);
                std::atexit(destroy);
            }

            return m_pInstance;
        }

        static void destroy() {
            if (m_pInstance) {
                delete m_pInstance;
                m_pInstance = nullptr;
            }
        }

    private:
        Singleton();
        ~Singleton();

    private:
        static Object           *m_pInstance;
        static pthread_once_t   m_thid_once;
};

template <typename Object>
Object * Singleton<Object>::m_pInstance = nullptr;

template <typename Object>
pthread_once_t Singleton<Object>::m_thid_once = PTHREAD_ONCE_INIT;

#endif // __NATSUME_Singleton_h__